package com.wakala.employment.fragment.finder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.google.common.collect.Lists;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.leaf.library.StatusBarUtil;
import com.wakala.employment.R;
import com.wakala.employment.adapter.jobCategory.CategoryConfigInfo;
import com.wakala.employment.adapter.jobCategory.ClassifyDetailAdapter;
import com.wakala.employment.adapter.jobCategory.ItemHeaderDecoration;
import com.wakala.employment.adapter.jobCategory.JobCategoryAttrTreeVo;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.adapter.jobCategory.RightBean;
import com.wakala.employment.adapter.jobCategory.RvListener;
import com.wakala.employment.adapter.jobCategory.SortAdapter;
import com.wakala.employment.adapter.jobCategory.SortBean;
import com.wakala.employment.adapter.jobCategory.TagSelectListener;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobCategoryBinding;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.CategoryMenuVo;
import com.wakala.employment.utils.DataUtil;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.kongzue.dialogx.dialogs.PopTip.tip;

import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link JobCategoryFragment} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class JobCategoryFragment extends BaseFragment<FragmentJobCategoryBinding> implements View.OnClickListener {

    private final String TAG = "JobCategoryFragment";


    private int requestCode;

    private int resultSize=5;

    /**
     * 调用传参，
     * type =JOBFINDER 从首页找活来，只能选择一个工种，点解确定后跳转到 JobListFragment页面
     */
    private String type;
    /**
     * 自定义加载对话框
     */
    private CustomDialog customDialog = null;//搜索市等待对话框


    private RecyclerView rvSort;
    private SortAdapter mLeftRvAdapter;

    private int targetPosition;//点击左边某一个具体的item的位置
    private boolean isMoved;

    private LinearLayoutManager mLinearLayoutManager;
    //-----------------------
    private RecyclerView rvDetail;

    private ClassifyDetailAdapter mRightRvAdapter;
    private LinearLayoutManager mDetailLinearLayoutManager;


    private JobCategoryTreeVo leftCategoryBean = null;
    private JobCategoryTreeVo rightCategoryBean = null;

    private List<JobCategoryTreeVo> leftCategoryList =new ArrayList<>();
    private List<JobCategoryTreeVo> rightCategoryList =new ArrayList<>();

    private Map<String,FlowTagLayout> flowTagLayoutMap = new HashMap<>();


    private ItemHeaderDecoration mDecoration;
    /**
     * 选择的属性-》属性值 Map
     */
    private Map<Integer,List<JobCategoryAttrTreeVo>> selectedResultMap = new HashMap<>();
    //------------------
    //tagView布局管理器
    TagContainerLayout mTagContainerLayout;
    private ArrayList<String> tagLayoutTags = new ArrayList<>();

    /**
     * 选择的工种
     */
    private ArrayList<JobCategoryTreeVo> selectedJobList = new ArrayList<>();



    @NonNull
    @Override
    protected FragmentJobCategoryBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentJobCategoryBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("工种分类");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        //initArgs执行时间早于initView
        requestCode =getRequestCode();
        if(requestCode == Constants.REQ_RESULT_111){
            resultSize = 1;
        }
        //
        type = getArguments().getString("type");
        if(isTypeJobFinder()){
            resultSize = 1;
        }
    }
    private Boolean isTypeJobFinder(){
        if(!StringUtils.isEmpty(type)){
            if(type.equals("JOBFINDER")){
                return true;
            }
        }
        return false;
    }
    @Override
    protected void initListeners() {

    }

    @Override
    protected void initViews() {
        initCustomDialog();
        //设置清除按钮 默认魏 disabled状态，当选择的工种类型列表不为空时才可以点击，进行清除操作，
        //当工种类型选择列表为空时设置清除按钮魏 disabled状态。
        binding.btnClearOptions.setEnabled(false);
        binding.btnClearOptions.setOnClickListener(this);
        binding.btnConfirmOptions.setOnClickListener(this);
        binding.flKindShow.setVisibility(View.GONE);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        //初始化左侧列表数据
        //--------------
        rvSort = binding.rvSort;
        rvSort.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL);
        rvSort.addItemDecoration(decoration);
        mLeftRvAdapter = new SortAdapter(getContext(), leftCategoryList, new LeftRvListener());
        rvSort.setAdapter(mLeftRvAdapter);
        //---初始化右侧列表数据-----------
        rvDetail = binding.rvDetail;
        mDetailLinearLayoutManager =  new LinearLayoutManager(getContext());
        rvDetail.setLayoutManager(mDetailLinearLayoutManager);
        //======================================右侧工种详情列表+tagView
        mRightRvAdapter = new ClassifyDetailAdapter(getContext(), rightCategoryList, new RightRvListener(),new RightTagSelectListener());
        rvDetail.setAdapter(mRightRvAdapter);

        //初始化tagViewLayout
        mTagContainerLayout = (TagContainerLayout) findViewById(R.id.tagcontainerLayout);
        mTagContainerLayout.setCrossColor(getResources().getColor(R.color.black30));
        mTagContainerLayout.setOnTagClickListener(new TagView.OnTagClickListener() {

            @Override
            public void onTagClick(int position, String text) {
                tip(""+position);
            }

            @Override
            public void onTagLongClick(int position, String text) {

            }

            @Override
            public void onSelectedTagDrag(int position, String text) {

            }

            @Override
            public void onTagCrossClick(int position) {
                //tip(""+position);
                if (position < mTagContainerLayout.getChildCount()) {
                    String tagText = mTagContainerLayout.getTagText(position);
                    mTagContainerLayout.removeTag(position);
                    Log.i("TAG",tagText);
                    tagLayoutTags.remove(tagText);
                    selectedJobList.removeIf(item->item.getName().equals(tagText));
                    //

                    FlowTagLayout flowTagLayout =flowTagLayoutMap.get(tagText);
                    List<Integer> postSelectedIndex = new ArrayList<>();
                    if(null!=flowTagLayout){
                       List<Integer> selectedIndexList =  flowTagLayout.getSelectedIndexs();
                        for (int index : selectedIndexList) {
                            JobCategoryTreeVo attrTreeVo = (JobCategoryTreeVo)flowTagLayout.getAdapter().getItem(index);
                            if(!attrTreeVo.getName().equals(tagText)){
                                postSelectedIndex.add(index);
                            }
                        }

                        if(!postSelectedIndex.isEmpty()){
                            flowTagLayout.setSelectedPositions(postSelectedIndex);
                        }else {
                            flowTagLayout.clearSelection();
                        }
                    }
                }
                if(mTagContainerLayout.getChildCount()<=0){
                    binding.flKindShow.setVisibility(View.GONE);
                    binding.btnClearOptions.setEnabled(false);
                }
                binding.tvSelectedCountTip.setText("已选择"+mTagContainerLayout.getChildCount()+"/"+resultSize);
            }
        });

        //
        getJobCategoryTreeAll();

    }

    /**
     * 初始化加载对话框
     */
    private void initCustomDialog() {
        //初始化加载等待对话框
        customDialog = CustomDialog.build()
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_layout_spinkit) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {

                    }
                });
    }

    private void setChecked(int position, boolean isLeft) {
        Log.d(TAG + "-------->p", String.valueOf(position));
        if (isLeft) {
            mLeftRvAdapter.setCheckedPosition(position);
            //此处的位置需要根据每个分类的集合来进行计算
            int count = 0;
            for (int i = 0; i < position; i++) {
                count += leftCategoryBean.getChild().size();
            }
            count += position;
            //mSortDetailFragment.setData(count);
            //ItemHeaderDecoration.setCurrentTag(String.valueOf(targetPosition));//凡是点击左边，将左边点击的位置作为当前的tag
        } else {
            if (isMoved) {
                isMoved = false;
            }
            mLeftRvAdapter.setCheckedPosition(position);
            //ItemHeaderDecoration.setCurrentTag(String.valueOf(position));//如果是滑动右边联动左边，则按照右边传过来的位置作为tag

        }
        moveToCenter(position);

    }

    /**
     * 右侧工种列表，叶子工种tag点击事件处理
     */
    class RightTagSelectListener implements TagSelectListener{
        /**
         *
         * @param flowTagLayout tagLayout组件
         * @param i 点击的第几个tag （tag索引） 对应tagAdapter的列表数据的索引
         * @param selectedList  点就后(包含当前点击的tag)tag选中的id列表
         */
        @Override
        public void onItemSelect(FlowTagLayout flowTagLayout, int i, List<Integer> selectedList) {

            JobCategoryTreeVo thatTagTreeVo = (JobCategoryTreeVo)flowTagLayout.getAdapter().getItem(i);
            if(selectedList.contains(i)){
                //flowTagLayout的第i个tag被选中
                //Toaster.show("选中:"+thatTagTreeVo.getName());
                if(tagLayoutTags.size() >=resultSize){
                    Toaster.show("最多可以选择"+resultSize+"个工种");
                    return;
                }
                if(tagLayoutTags.contains(thatTagTreeVo.getName())){
                    Toaster.show("该工种已选择");
                }else {
                    tagLayoutTags.add(thatTagTreeVo.getName());
                    selectedJobList.add(thatTagTreeVo);
                    //
                    flowTagLayoutMap.put(thatTagTreeVo.getName(),flowTagLayout);
                }

            }else {
                //取消flowTagLayout的第i个tag
                //Toaster.show("取消:"+thatTagTreeVo.getName());
                tagLayoutTags.removeIf(item->item.equals(thatTagTreeVo.getName()));
                selectedJobList.removeIf(item->item.getName().equals(thatTagTreeVo.getName()));
                //
                flowTagLayoutMap.remove(thatTagTreeVo.getName());
            }
            mTagContainerLayout.setTags(tagLayoutTags);
            if(mTagContainerLayout.getChildCount()>0){
                binding.flKindShow.setVisibility(View.VISIBLE);
                binding.btnClearOptions.setEnabled(true);
            }else {
                binding.flKindShow.setVisibility(View.GONE);
                binding.btnClearOptions.setEnabled(false);
            }
            binding.tvSelectedCountTip.setText("已选择"+mTagContainerLayout.getChildCount()+"/"+resultSize);
        }
    }

    class  LeftRvListener  implements RvListener{

        @Override
        public void onItemClick(int id, int position) {
            //PopTip.show("这是一个提示").showShort();
            isMoved = true;
            targetPosition = position;

            //刷新分类列表数据为当前一点击的右侧一级分类的二级子类
            leftCategoryBean = leftCategoryList.get(position);
            rightCategoryList.clear();
            rightCategoryList.addAll(leftCategoryBean.getChild());
            setChecked(position, true);
            //取消加入titile 否则二级分类索引会乱，或者SortBean的二级分类三级分类都加上code
            XUtil.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mRightRvAdapter.notifyDataSetChanged();
                }
            });

        }
    }

    class RightRvListener implements RvListener{

        @Override
        public void onItemClick(int id, int position) {
          /*  rightCategoryBean = rightCategoryList.get(position);
            //-- 选择的分类添加在已选择部分
            if(mTagContainerLayout.getChildCount()>=5){
                Toaster.show("最多选择5个工种");
            }else if(tagLayoutTags.contains(rightCategoryBean.getName())){
                Toaster.show("该工种已添加");
            }else {
                tagLayoutTags.add(rightCategoryBean.getName());
                selectedJobList.add(rightCategoryBean);
                mTagContainerLayout.addTag(rightCategoryBean.getName());
            }
                    *//* if(mTagContainerLayout.getChildCount()<5 && !tagLayoutTags.contains(mCategoryData.get(position).getName())){
                         tagLayoutTags.add(mCategoryData.get(position).getName());
                         mTagContainerLayout.addTag(mCategoryData.get(position).getName());
                     }else {
                         Toaster.show("最多选择5个工种");
                     }*//*
            if(mTagContainerLayout.getChildCount()>0){
                binding.flKindShow.setVisibility(View.VISIBLE);
                binding.btnClearOptions.setEnabled(true);
            }*/
        }
    }

    /**
     * 获取工种分类数
     */
    @SuppressLint("CheckResult")
    private void getJobCategoryTreeAll(){
        customDialog.show();
        XHttpProxy.proxy(TestApi.IJobCategoryService.class)
                .listJobCategoryTreeAll()
                .subscribeWith(new NoTipRequestSubscriber<List<JobCategoryTreeVo>>() {

                    @Override
                    protected void onSuccess(List<JobCategoryTreeVo> jobCategoryTreeVoList) {
                        Log.i(TAG,"-------------获取工种分类树------------------");
                        Toaster.show("数据加载成功");
                        leftCategoryList.clear();
                        leftCategoryList.addAll(jobCategoryTreeVoList);
                        rightCategoryList.clear();
                        rightCategoryList.addAll(jobCategoryTreeVoList.get(0).getChild());
                        XUtil.runOnUiThread(() -> {
                            mLeftRvAdapter.notifyDataSetChanged();
                            mRightRvAdapter.notifyDataSetChanged();
                            int i1=mLeftRvAdapter.getItemCount();
                            int i2=mRightRvAdapter.getItemCount();
                        });
                        customDialog.dismiss();
                        Log.i(TAG,"-------------获取工种分类树------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);;
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG,"-------------获取工种分类树-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        customDialog.dismiss();
                    }

                });
    }

    //将当前选中的item居中
    private void moveToCenter(int position) {
        //将点击的position转换为当前屏幕上可见的item的位置以便于计算距离顶部的高度，从而进行移动居中
        View childAt = rvSort
                .getChildAt(position - mLinearLayoutManager.findFirstVisibleItemPosition());
        if (childAt != null) {
            int y = (childAt.getTop() - rvSort.getHeight() / 2);
            rvSort.smoothScrollBy(0, y);
        }

    }



    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.btn_clear_options){
            //清除选择
            mTagContainerLayout.removeAllTags();
            tagLayoutTags.clear();
            selectedJobList.clear();
            //恢复view初始状态
            binding.btnClearOptions.setEnabled(false);
            binding.flKindShow.setVisibility(View.GONE);
        }
        if(id==R.id.btn_confirm_options){
            if(tagLayoutTags.isEmpty()){
                //tip("请选择工种");
                Toaster.show("请选择工种");
            }else {
                //确认选择
                //发送确认选择工种数据广播
                // Bundle backBundle =new Bundle();
                //backBundle.putString("name","张三");
                //popToBack("RecruitIssueFragment",backBundle);
                if(isTypeJobFinder()){
                    CategoryMenuVo categoryMenuVo = new CategoryMenuVo();
                    categoryMenuVo.setTarget(1);
                    categoryMenuVo.setName(selectedJobList.get(0).getName());
                    categoryMenuVo.setJobCategoryNames(Lists.newArrayList(selectedJobList.get(0).getName()));
                    categoryMenuVo.setUrl(String.valueOf(selectedJobList.get(0).getId()));
                    openNewPage(JobListFragment.class,"data",categoryMenuVo);
                }else{
                    Intent intent=new Intent();
                    intent.putStringArrayListExtra("tagLayoutTags",tagLayoutTags);
                    //intent.putExtra("selectedJobList",selectedJobList.toArray(new JobCategoryTreeVo[0]));
                    intent.putParcelableArrayListExtra("selectedJobList",selectedJobList);
                    setFragmentResult(requestCode,intent);
                    popToBack();
                }

            }

        }
    }




}